/**
 *
 * 调用示例：
 * let formData = new FormData()
 *formData.append("id",1060)
 *
 *$http.post(url,formData,headers).then((json) => {
 * //处理 请求success
 *  	if(json.code === 0 ){
 *          //我们假设业务定义code为0时，数据正常
 *      }else{
 *           //处理自定义异常
 *          console.log(json.msg);
 *      }
 * },(json)=>{
 *   //处理请求fail
 *
 * })
 */
import Fun from "./index";
import base64_encode from "../utils/base64_encode";
import { Toast } from "vant";
// var heads = { 'Content-Type': 'application/json' };
// import store from "../store/index";
import storeOption from "../store";
const language = require("../utils/language.json"); //加载本地数据文件
import {unfinishedTaskFn} from './unfinished-task.js';

axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
window.yzFirstlogin = 1; //判断是否第一个请求的接口  带上basic_info的数据
window.firstLogin = 0; //判断是否已经跳转了登录
window.yzValidate_page = 0; //判断是否需要跳转邀请页面 || 实名认证 || 默认地址是否设置 带上validate_page的数据,

window.TencentGDT = window.TencentGDT || []; //优量汇广告
window.GDTArr = []; //存储广告

//以下是不需要登录的页面
// "#/diyform/", 自定义表单页注释删除原因：没登录获取不到会员id提交不了表单[44944]
const passList = ["#/login?", "#/register?", "#/findpwd?", "#/category?", "#/user_agreement?", "#/member/editmobile/", "#/registerAgreement?"];

// 创建一个 store 对象用于管理应用状态
const store = new Vuex.Store(storeOption);

function wxRedirectLogin(url) {
  if(Fun.isWalletApp()) return loginWalletApp();
  store.commit("setWXlogined", 0);//需要登录
  const noAutoRedirectLogin = ["#/member?", "#/cart?", "/member/extension?",'/AuthorizedLogin?'];//页面有自己的登录显示逻辑
  for (let i = 0; i < noAutoRedirectLogin.length; i++) {
    if (window.location.href.indexOf(noAutoRedirectLogin[i]) > -1) {
      window.firstLogin = 0;
      return false;
    }
  }
  let _yz_redirect = window.location.href.indexOf('/userinfo?') < 0 ? base64_encode(url): '';//不处理userinfo? 更新资料页面，防止死循环一直在这两个页面跳转
  let _authorizedPage = Fun.getSiteRoot() + "/addons/yun_shop/" + "?menu#" + "/AuthorizedLogin?i=" + Fun.getKeyByI() + "&mid=" + Fun.getKeyByMid() + "&type=" + Fun.getTyep() + "&yz_redirect=" + _yz_redirect;
  window.location.href = _authorizedPage;//跳转微信授权链接
}
function isInWechatMp(){
  return navigator.userAgent.match(/miniprogram/i) || window._wxjs_environment === 'miniprogram'
}

function isPassUrl() {
  for (let i = 0; i < passList.length; i++) {
    // 编程式
    if (window.location.href.indexOf(passList[i]) > -1) {
      return true;
    }
  }

  return false;
}

function jumpH5(data) {
  // 跳转PC端路由
  const PCNotrouter = [
    { h5: "/member", pc: "/order" },
    { h5: "/member/orderList/0", pc: "/order" },
    { h5: "/member/orderdetail/", pc: "/order" },
    { h5: "/knowledge/knowledge_list", pc: "/knowledge/knowledge_detail/-1" }
  ];

  const PCrouter = [
    "/login",
    "/register",
    "/findpwd",
    "/home",
    "/category",
    "/category_child/",
    "/search?",
    "/goods/",
    "/cart",
    "/goodsorder",
    "/supplier_shop2/",
    "/coupon/coupon_index",
    "/coupon/coupon_store",
    "/member/integral_v2",
    "/member/balance",
    "/member/address",
    "/member/extension",
    "/member/workerApply",
    "/member/workerOrderlist",
    "/member/workerOrderDetail/",
    "member/userOrderlist",
    "/member/userOrderDetail/",
    "/catelist/",
    "/application_market",
    "/member/collection",
    "/notice",
    "/articleContent/",
    "/member/coursedetail/",
    "/goodsGroup/",
    "/authorizationQuery",
    "/knowledge/home",
    "/knowledge/knowledge_whole",
    "/knowledge/knowledge_search",
    "/knowledge/knowledge_detail/",
    "/microHome/microIndex",
    "/microhomepage",
    "/microRelease",
    "/microcommentdetails",
    "/member/sign",
    "/videoList",
    "/VideoList",
    "/videoDetail",
    "/releaseVideo",
    "/time_page"
  ];

  // 不需要跳转但是匹配的H5路由
  const notMatch = ["/o2o/home", "/entry_orders/home", "/microShop/home", "/o2o/category/", "/cart_share"];

  let path = "/" + window.location.href.match(/#\/(\S*)\?/)[1];
  let fullPath = window.location.href.match(/#\/(\S*)?/)[1];
  let isPCrouter = false;

  PCrouter.map(item => {
    if (path.indexOf(item) > -1 && notMatch.filter((route)=>{
      return path.indexOf(route) > -1;
    }).length <= 0) {
      isPCrouter = true;
    }
  });

  // 移动端跳转PC端
  if (isPCrouter) {
    if(data.goods_type == 'course_supply') return;//临时处理供应链课程商品，pc还没弄
    Fun.browserRedirect(`${Fun.getSiteRoot()}/plugins/shop_server/${fullPath}`);
  } else {
    let notFlag = "";
    PCNotrouter.map(item => {
      // 只能这样匹配  否则包含/member的都会跳转
      if (item.h5.indexOf(path) > -1) {
        notFlag = item.pc;
      }
    });

    if (notFlag) {
      // http://localhost:82
      if (notFlag === "/knowledge/knowledge_detail/-1") {
        Fun.browserRedirect(`${Fun.getSiteRoot()}/plugins/shop_server${notFlag}?i=${Fun.getKeyByI()}&mid=${Fun.getKeyByMid()}&base_id=${Fun.getKey("base_id")}`);
      } else {
        Fun.browserRedirect(`${Fun.getSiteRoot()}/plugins/shop_server${notFlag}?i=${Fun.getKeyByI()}&mid=${Fun.getKeyByMid()}`);
      }
    }
  }
}

function tempInfo(data) {
  // let isLocation = false;
  if (!data) return;

  if (data.memberinfo) {
    //可用爱心值
    window.localStorage.setItem("usable", data.memberinfo.usable);
    window.localStorage.setItem("uid", data.memberinfo.uid);
  }

  if (!data.default) {
    // 新装修
    if (data.item.is_decorate === 1) {
      window.isDecorate = true;
      // store.commit("setNewDiyData", data.item);
      // if (data.item.page_info && data.item.page_info.page_title) {
      //   data.item.janst = data.item.page_info.page_title;
      // }else {
      //   data.item.janst = "";
      // }
    } else {
      window.isDecorate = false;
      // for (let j of data.item.data) {
      //   j.temp = "show" + j.temp;
      //   if (
      //     j.temp == "showlocation" ||
      //     j.temp == "showstore" ||
      //     j.temp == "showbusiness"
      //   ) {
      //     isLocation = true;
      //   }
      // }
      // 设置的标题（装修）
      // if (data.item.pageinfo) {
      //   data.item.janst = data.item.pageinfo.params.title;
      // }
    }
  }

  if (data.item.is_decorate !== 1) {
    // 底部导航设置
    data.item.menus = "";
  }
  data.item.janst = data.mailInfo.name;

  window.localStorage.setItem("integral", Fun.getCustomTextLang('member_center.credit1','积分'));

  if (data.plugin && data.plugin.new_member_prize && data.plugin.new_member_prize.prize) {
    //满足新人奖，显示弹窗
    // store.commit("setNewcomerAward", true);
    window.localStorage.setItem("new_member_prize", JSON.stringify(data.plugin.new_member_prize));
  }

  store.commit("tempIndex", data);
  // if (data.item.pageinfo) {
  //   store.commit("setWatchDiypage", data.item.pageinfo.params.allowauth);
  // }
  // window.localStorage.setItem("tempIndex", JSON.stringify(data));  存vuex里不存localStorage
}
function authYear(){
  let yz_redirect = encodeURIComponent(`${document.location.href}&scope=yearendbox`);
  $http.get("plugin.year-end-box.citic.oauth.getAppid").then(response => {
    if (response.result === 1) {
      let uploadUrl = `https://uc.creditcard.ecitic.com/citiccard/newucwap/oauth/getAccessCode.do?appid=${response.data}&scope=queryUserInfo&returnUrl=${yz_redirect}`;
      window.location.href = uploadUrl
    } else {
      Toast(response.msg);
    }
  });
}

function loginWalletApp(){
  window.WindVane.call("SBase","getUserInfo",{},(e)=>{
    //例如获取用户手机号e.result.mobile
    console.info("getUserInfo success=",e);
    $http.post("member.login.index", e.result ,'.').then(response => {
      if (response.result !== 1) {
        return Toast(response.msg);
      }
      window.WindVane.call('SBase','refreshPage',{url: ''},function(e){
        console.log('login success:'+JSON.stringify(e));
      },function(e){
        console.log('login failure:'+JSON.stringify(e));
      });
    });
  },(e)=>{
    console.info("getUserInfo fail=",e);
  });
}

async function getInvite(data) {
  sessionStorage.setItem('validate_page',JSON.stringify(data));
  if(data.is_login === 1) window.localStorage.i = Fun.getKeyByI();//记录当前已授权登录的平台id
  if ((data.is_invite === 1 || data.invite_mobile === 1) && (data.real_name_auth_is_open === 1 && data.is_auth === 1) && data.bind_address.is_bind_address == 1  && data.is_level_compel == 0) {
    window.yzValidate_page = 1;
  }
  if(window.location.href.indexOf('/usr/missionCenter?') < 0) unfinishedTaskFn(data);//处理一些需要跳转页面的业务逻辑（绑定手机、邀请码等等）
  if (data.is_login === 1 && data.lsp_wallet_site == '') {
    store.commit("setWallerBind", true);// 判断是否绑定过钱包地址，只适配钱包app，只有一个客户用
  }
}

function popularize_page_permission(){
  if (window.popularizeYZ) {
    let _wapURL = [5,1,7,8];//跳转到h5链接
    let _m = new Map([[5, 'wap'], [1, 'wechat'],[7, 'app'],[8, 'alipay'],]);
    let _type = Number(Fun.getTyep());
    if(_wapURL.indexOf(_type) >= 0){
      let _set = _m.get(_type);
      let _activeSet = window.popularizeYZ[_set];
      if (_activeSet.vue_route.indexOf(window.__lendApp__.$route.name) >= 0) {
        Toast('未开启推广权限');
        // 【#95927】修改为后台没有填写时，默认跳转首页，不跳404
        if (Fun.isTextEmpty(_activeSet.url)) {
          window.location.href = Fun.getSiteRoot() + "/addons/yun_shop/" + "?menu#" + "/404?i=" + Fun.getKeyByI() + "&type=" + Fun.getTyep() + "&mid=" + Fun.getKeyByMid();
        } else {
          window.location.href = _activeSet.url;
        }
      }
    } else if (Fun.getTyep() == "2") {
      if (window.popularizeYZ.mini.vue_route.indexOf(window.__lendApp__.$route.name) >= 0) {
        Toast('未开启推广权限');
        if (Fun.isTextEmpty(window.popularizeYZ.mini.url)) {
          window.location.href = Fun.getSiteRoot() + "/addons/yun_shop/" + "?menu#" + "/404?i=" + Fun.getKeyByI() + "&type=" + Fun.getTyep() + "&mid=" + Fun.getKeyByMid();
        } else {
          wx.miniProgram.navigateTo({
            url: window.popularizeYZ.mini.url
          });
        }
      }
    }
  }
}
// 记录是否调用过getLanguage
let isGetLanguage = false;
function getLanguage(data) {
  if(isGetLanguage) return;
  isGetLanguage = true;
  $i18n.mergeLocaleMessage("en", data && data.en ? data.en : language.en);
}

// getLanguage(language); // 先调用一次初始化

function translateJsInit() {
  translate.setAutoDiscriminateLocalLanguage();
  translate.selectLanguageTag.show = false;
  translate.service.use('client.edge'); //设置机器翻译服务通道，直接客户端本身，不依赖服务端 。相关说明参考 http://translate.zvo.cn/43086.html
  translate.listener.start();    //开启html页面变化的监控，对变化部分会进行自动翻译。注意，这里变化区域，是指使用 translate.setDocuments(...) 设置的区域。如果未设置，那么为监控整个网页的变化
  translate.request.listener.start();
  translate.request.listener.delayExecuteTime = 1000;
  translate.execute();//进行翻译
}

let abortSignalControllers = [];
export default {
  // 封装axios的post请求
  fetchUrl(url, params, message) {
    if (message == null || message == undefined) {
      storeOption.state.isloadding = false;
    } else {
      storeOption.state.isloadding = true;
    }

    return new Promise((resolve, reject) => {
      axios
        .get(url, { params: params.params, headers: params.headers })
        .then(response => {
          storeOption.state.isloadding = false;
          resolve(response.data);
        })
        .catch(error => {
          storeOption.state.isloadding = false;
          reject(error);
        });
    });
  },
  // 封装的 GET请求
  get(url, params, message) {
    if (!url) {
      console.log("输入url为空");
      return;
    }
    let i = Fun.getKeyByI();
    let mid = Fun.getKeyByMid();
    let type = Fun.getTyep();
    let shop_id = Fun.getKeyByMicroShopId();
    let v_id = window.localStorage.getItem("vid");
    let cicleInvitationId = window.localStorage.getItem("circle_invitation_id");
    let sessionid = Fun.getSession();
    let token = Fun.getToken();
    let webToken = localStorage.getItem("token");
    let uid = localStorage.getItem("loginUid");
    let uuid = window.localStorage.uuid;
    // let _thirdpartySSH = Fun.getKey("scope") != 'yearendbox' && Fun.getKey("scope") != 'jinepay' && Fun.getKey("scope") != 'yzx_pay';//第三方免登录 临时更改年末礼盒
    let _thirdpartySSH = Fun.getKey("scope") != 'jinepay' && Fun.getKey("scope") != 'yzx_pay';//第三方免登录
    if (!uuid) {
      uuid = 0;
    }
    let baseUrl = "/addons/yun_shop/api.php?i=" + i + "&uuid=" + uuid + "&type=" + type;
    if (mid) {
      baseUrl += "&mid=" + mid;
    }
    if (Fun.getKey("alipay_token")){
      baseUrl += `&min_token=${Fun.getKey("alipay_token")}`;
      try {
        my.getEnv(function (res) {
          console.log(res.miniprogram,'+++my.getEnv'); //true
          window.alipaymini = res.miniprogram;
        });
      } catch (error) {
        console.log(error,'+++my.getEnv')
      }
    }
    if (shop_id) {
      baseUrl += "&shop_id=" + shop_id;
    }
    // let ua = window.navigator.userAgent.toLowerCase();
    if (isInWechatMp()) {
      baseUrl += "&miniProgram=1";
      let min_token = sessionStorage.getItem("min_token") || null; //小程序web-view免登录
      if(min_token) baseUrl = `${baseUrl}&min_token=${min_token}`;
    }

    let supplier_alone_id = Fun.getKey('supplier_alone_id') || sessionStorage.getItem("supplier_alone_id") || null; //供应商独立模板，获取供应商id
    if(supplier_alone_id){
      baseUrl += "&supplier_alone_id=" + supplier_alone_id + "&locale_code=" + $i18n.locale;
    }

    // console.log("Fun.isWXWork()", Fun.isWXWork()); 只根据链接的client参数来判断企业侧边栏环境  不用isWXWork crop_id是企业id
    if (Fun.getKey("client") === "work" || window.localStorage.getItem("client")) {
      // 判断是否从企业微信侧边栏进入
      window.localStorage.setItem("client", "work");
      baseUrl += "&client=work";
      // baseUrl += "&crop_id="+ Fun.getKey("crop_id");
    }

    baseUrl += "&version=v1.1.149";

    if (Fun.isCPS() && Fun.isCPSAPPI()) {
      baseUrl += "&cps_h5=1";
    }

    //specialFilterApi 一些需要特殊过滤的接口,这些不需要validate_page
    let specialFilterApi = [
      'shop.FrontendError.do-log','member.login.index','member.member.wxJsSdkConfig','member.login.login-mode','home-page.getCaptcha',
      'member.register.sendCodeV2','member.member.prepBind','member.member.bindMobile','plugin.car-manage.frontend.controllers.car.bind-car'
    ]
    let _isSpecialFilterApi = true;
    for (let i = 0; i < specialFilterApi.length; i++) {
      if (url.indexOf(specialFilterApi[i]) > -1 ) {
        _isSpecialFilterApi = false;//拦截，该接口不需要传validate_page
      }
    }

    if (
      window.yzFirstlogin === 0 &&
      window.yzValidate_page === 0 &&
      _isSpecialFilterApi &&
      url.indexOf("plugin.diyform.api.diy-form.save-diy-form-data") < 0
    ) {
      baseUrl = baseUrl + "&validate_page=1";
    }
    if ((window.yzFirstlogin === 1 && _isSpecialFilterApi) ||url.indexOf("finance.income-page.index") >= 0) {
      window.yzFirstlogin = 0;
      baseUrl = baseUrl + "&basic_info=1&validate_page=1";
      // if(Fun.getKey("scope") == 'yearendbox'){
      //   baseUrl += `&scope=yearendbox&accessCode=${Fun.getKey("accessCode")}`;
      // }
      if(Fun.getKey("scope") == 'jinepay'){
        baseUrl += `&scope=jinepay&data=${Fun.getKey("data")}`;
      }
      if(Fun.getKey("scope") == 'yzx_pay'){
        baseUrl += `&scope=yzx_pay&yzx_token=${Fun.getKey("yzx_token")}`;
      }
    } else if (!store.state.temp.mailInfo) {
      baseUrl = baseUrl + "&basic_info=1";
      // if(Fun.getKey("scope") == 'yearendbox'){
      //   baseUrl += `&scope=yearendbox&accessCode=${Fun.getKey("accessCode")}`;
      // }
      if(Fun.getKey("scope") == 'jinepay'){
        baseUrl += `&scope=jinepay&data=${Fun.getKey("data")}`;
      }
      if(Fun.getKey("scope") == 'yzx_pay'){
        baseUrl += `&scope=yzx_pay&yzx_token=${Fun.getKey("yzx_token")}`;
      }
    }

    if (v_id) {
      baseUrl = baseUrl + "&vid=" + v_id;
    }
    if (cicleInvitationId) {
      baseUrl += "&circle_invitation_id=" + cicleInvitationId;
    }
    if (window.localStorage.getItem('app_id')){
      baseUrl += `&app_id=${window.localStorage.getItem('app_id')}`
    }

    let app_token = "";
    if (Fun.isCPS()) {
      let ua = window.navigator.userAgent.toLowerCase();
      if (ua.indexOf("yz_cps02") > -1) {
        if (Fun.isIosOrAndroid() === "ios") {
          app_token = getKeyIIOS().token;
        } else {
          if (getKeyIAndroid()) {
            app_token = getKeyIAndroid().token;
          }
        }
      }
    }

    if (message == null || message == undefined) {
      storeOption.state.isloadding = false;
    } else {
      storeOption.state.isloadding = true;
    }

    if (
      window.location.href.indexOf("scope") > -1 &&
      window.location.href.indexOf("appid") > -1 &&
      window.location.href.indexOf("mob_user") > -1 &&
      window.location.href.indexOf("timestamp") > -1 &&
      window.location.href.indexOf("sign") > -1
    ) {
      if (Fun.isCPS() && !Fun.isCPSAPPI()) {
        baseUrl += "&route=";
        console.log("cps 不同域名或i");
      } else {
        if (app_token) {
          baseUrl += "&app_token=" + app_token;
        }
        if (window.location.href.indexOf("open_id") > -1) {
          baseUrl += `&open_id=${Fun.getKey("open_id")}`;
        }
        baseUrl +=
          "&scope=" +
          Fun.getKey("scope") +
          "&appid=" +
          Fun.getKey("appid") +
          "&mob_user=" +
          Fun.getKey("mob_user") +
          "&timestamp=" +
          Fun.getKey("timestamp") +
          "&sign=" +
          Fun.getKey("sign") +
          "&route=";
        if (!window.localStorage.getItem("mob_user") && Fun.getKey("mob_user") != 0) {
          setTimeout(() => {
            window.localStorage.setItem("scope", Fun.getKey("scope"));
            window.localStorage.setItem("appid", Fun.getKey("appid"));
            window.localStorage.setItem("mob_user", Fun.getKey("mob_user"));
            window.localStorage.setItem("timestamp", Fun.getKey("timestamp"));
            window.localStorage.setItem("sign", Fun.getKey("sign"));
          }, 200);
        }
        console.log("freeLogin cps");
      }
    } else if (
      window.localStorage.getItem("scope") &&
      window.localStorage.getItem("appid") &&
      window.localStorage.getItem("mob_user") &&
      window.localStorage.getItem("timestamp") &&
      window.localStorage.getItem("sign")
    ) {
      if (app_token) {
        baseUrl += "&app_token=" + app_token;
      }
      baseUrl +=
        "&scope=" +
        window.localStorage.getItem("scope") +
        "&appid=" +
        window.localStorage.getItem("appid") +
        "&mob_user=" +
        window.localStorage.getItem("mob_user") +
        "&timestamp=" +
        window.localStorage.getItem("timestamp") +
        "&sign=" +
        window.localStorage.getItem("sign") +
        "&route=";
      console.log("freeLogin2");
    } else if (
      window.location.href.indexOf("scope") > -1 &&
      window.location.href.indexOf("appid") > -1 &&
      window.location.href.indexOf("mob_parent") > -1 &&
      window.location.href.indexOf("mob_user") > -1 &&
      window.location.href.indexOf("timetamp") > -1 &&
      window.location.href.indexOf("sign") > -1
    ) {
      baseUrl +=
        "&scope=" +
        Fun.getKey("scope") +
        "&appid=" +
        Fun.getKey("appid") +
        "&mob_parent=" +
        Fun.getKey("mob_parent") +
        "&mob_user=" +
        Fun.getKey("mob_user") +
        "&timetamp=" +
        Fun.getKey("timetamp") +
        "&sign=" +
        Fun.getKey("sign") +
        "&route=";
      if (!window.localStorage.getItem("mob_user") && Fun.getKey("mob_user") != 0) {
        window.localStorage.setItem("scope", Fun.getKey("scope"));
        window.localStorage.setItem("appid", Fun.getKey("appid"));
        window.localStorage.setItem("mob_parent", Fun.getKey("mob_parent"));
        window.localStorage.setItem("mob_user", Fun.getKey("mob_user"));
        window.localStorage.setItem("timetamp", Fun.getKey("timetamp"));
        window.localStorage.setItem("sign", Fun.getKey("sign"));
      }
      console.log("haifen");
    } else if (
      window.localStorage.getItem("scope") &&
      window.localStorage.getItem("appid") &&
      window.localStorage.getItem("mob_parent") &&
      window.localStorage.getItem("mob_user") &&
      window.localStorage.getItem("timetamp") &&
      window.localStorage.getItem("sign")
    ) {
      baseUrl +=
        "&scope=" +
        window.localStorage.getItem("scope") +
        "&appid=" +
        window.localStorage.getItem("appid") +
        "&mob_parent=" +
        window.localStorage.getItem("mob_parent") +
        "&mob_user=" +
        window.localStorage.getItem("mob_user") +
        "&timetamp=" +
        window.localStorage.getItem("timetamp") +
        "&sign=" +
        window.localStorage.getItem("sign") +
        "&route=";
      console.log("haifen2");
    } else if (window.location.href.indexOf("#/cashier_pay/") > -1 && url.indexOf("member.login.check-login") < 0) {
      baseUrl += "&scope=base&route=";
    } else if (_thirdpartySSH && window.location.href.indexOf("#/home?") > -1 && url.indexOf("member.login.check-login") < 0) {
      baseUrl += "&scope=home&route=";
    } else if (_thirdpartySSH && window.location.href.indexOf("#/newDiy?") > -1 && url.indexOf("member.login.check-login") < 0) {
      baseUrl += "&scope=home&route=";
    } else if (_thirdpartySSH && (isPassUrl() == true && url.indexOf("member.login.check-login") < 0 && url.indexOf("member.member-cart.store") < 0) || url.indexOf("shop.FrontendError.do-log") > 0) {
      baseUrl += "&scope=pass&route=";
    } else {
      baseUrl += "&route=";
    }
    if (params) {
      let paramsArray = [];
      Object.keys(params).forEach(key => paramsArray.push(key + "=" + params[key]));
      url += "&" + paramsArray.join("&");
      url = baseUrl + url;
    } else {
      url = baseUrl + url;
    }

    if (token) {
      url = url + "&client_type=2&app_type=wechat" + "&3rd_session=" + sessionid + "&session_id=" + token;
    }

    console.log("===test url====", url);

    // Authorization要删
    let headers = {
      "Content-Type": "application/json",
      Authorization: "Basic " + base64_encode(uid + ":" + webToken)
    };

    if (window.new_page_comeIn != 2) {
      // 浏览足迹  new_page_comeIn == 2为页面第一个请求接口
      headers["local-url"] = `/${window.location.href.match(/\#\/(\S*)\?/)[1]}`;
      headers["full-url"] = `${window.location.href}`;
      window.new_page_comeIn = 2;
    }

    return new Promise(function(resolve, reject) {
      fetch(url, {
        method: "GET",
        headers: headers,
        credentials: "include"
      })
        .then(response => {
          if (response.ok) {
            return response.json();
          } else {
            reject({ status: response.status });
          }
          storeOption.state.isloadding = false;
        })
        .then(response => {
          storeOption.state.isloadding = false;
          if (response.result == 0 && !Fun.isTextEmpty(response.data) && response.data.status == "number") {
            window.location.href = Fun.getSiteRoot() + "/addons/yun_shop/" + "?menu#" + "/member?i=" + Fun.getKeyByI() + "&type=" + Fun.getTyep() + "&mid=" + Fun.getKeyByMid();
            Toast(response.msg);
            return;
          }
          if (response.result == 0 && !Fun.isTextEmpty(response.data) && response.data.status == -3) {
            window.location.href = Fun.getSiteRoot() + "/addons/yun_shop/" + "?menu#" + "/member/mandate";
            return;
          }
          if (response.result == 0 && !Fun.isTextEmpty(response.data) && response.data.status == -2) {
            window.location.href = Fun.getSiteRoot() + "/addons/yun_shop/" + "?menu#" + "/404";
            return;
          }
          if (response.result == 0 && !Fun.isTextEmpty(response.data) && (response.data.task_package_invite_code == -1 || response.data.task_package_real_name_auth == -1)){
            if(response.data.task_package_invite_code == -1) {
              let MinUrl = Fun.getSiteRoot() + "/addons/yun_shop/?menu#/taskPackage/middle?i=" + Fun.getKeyByI() + "&type=" + Fun.getTyep() + "&mid=" + Fun.getKeyByMid();
              window.location.href = MinUrl;
              return
            };
            if(response.data.task_package_real_name_auth == -1) {
              store.commit("setCallback", window.location.href);
              let MinUrl = Fun.getSiteRoot() + "/addons/yun_shop/?menu#/personBank?from=bindRealName&i=" + Fun.getKeyByI() + "&type=" + Fun.getTyep() + "&mid=" + Fun.getKeyByMid();
              window.location.href = MinUrl;
              return
            }
          }
          if (response.result == 0 && !Fun.isTextEmpty(response.data) && response.data.login_status != undefined && response.data.login_status == 0) {
            window.yzFirstlogin = 1;
            window.localStorage.setItem("isWxLogin", 1);
            if (!window.firstLogin) {
              window.firstLogin = 1;
              console.log("微信登录");
              let login_jump_url = response.data.login_url + "&yz_redirect=" + base64_encode(document.location.href);
              if (Fun.getKey("client") === "work" || window.localStorage.getItem("client")) {
                // 是否从企业微信侧边栏进入
                login_jump_url = response.data.login_url + "&crop_id="+ Fun.getKey("crop_id") + "&client=work&yz_redirect=" + base64_encode(document.location.href);
                window.location.href = login_jump_url;//企业微信不统一wxRedirectLogin跳转的原因：苹果电脑出现闪退，原因不详
                return;
              } else if(response.data.scope && response.data.scope == 'snsapi_base'){
                window.location.href = login_jump_url;//静默登录
                return;
              }
              wxRedirectLogin(document.location.href);
            }
            reject({ msg: "请登录" }); //直接报错
            return response;
          } else if (response.result == 0 && !Fun.isTextEmpty(response.data) && response.data.login_status != undefined && response.data.login_status == 1) {
            window.yzFirstlogin = 1;
            window.localStorage.setItem("isWxLogin", -1);
            if (document.location.href.indexOf("/login?") == -1) {
              let _locationHref = document.location.href;
              if (window.self !== window.top) {
                _locationHref = window.parent.location.href;//在iframe环境打开
              }
              sessionStorage.setItem("yz_redirect", base64_encode(_locationHref));
            }

            // try {
            //   let basic_info = JSON.parse(localStorage.getItem("yz_basic_info"))||{};
            //   let is_year_end_box_login = basic_info.plugin_setting&&basic_info.plugin_setting.is_year_end_box_login?basic_info.plugin_setting.is_year_end_box_login:false;
            //   if(is_year_end_box_login){
            //     authYear();
            //     return;
            //   }
            // } catch (error) {
            //   console.log("年末礼盒=====",error);
            // }

            if (!window.firstLogin) {
              console.log("跳入登录入口");
              if (Fun.isCPS() && Fun.isCPSAPPI()) {
                window.firstLogin = 1;
                if (Fun.isIosOrAndroid() === "ios") {
                  callIOS({ body: "callIOS" });
                } else {
                  callAndroid();
                }
                setTimeout(() => {
                  // 防止聚合APP切换不同公众号没有再次登录
                  window.firstLogin = 0;
                }, 3000);
              } else {
                window.location.href = Fun.getSiteRoot() + "/addons/yun_shop/" + "?menu#" + "/login?i=" + response.data.i + "&type=" + Fun.getTyep() + "&mid=" + response.data.mid;
              }
            }

            reject({ msg: "请登录" }); //直接报错
            return response;
          } else {
            if (response.basic_info) {
              localStorage.setItem("yz_basic_info", JSON.stringify(response.basic_info));
              if (response.basic_info.consolidated_payment) {
                localStorage.setItem("consolidated_payment", response.basic_info.consolidated_payment == "1" ? true : false);
              }
              if (response.basic_info.plugin_setting) {
                localStorage.setItem("plugin_setting", JSON.stringify(response.basic_info.plugin_setting));
              }
              // 跳转PC端代码
              if (!Fun.isWXWork() && response.basic_info.plugin_setting && response.basic_info.plugin_setting.pc_terminal && response.basic_info.plugin_setting.pc_terminal.enable == 1) {
                jumpH5(response.data);
              }
              // 跳转PC端代码end

              if (response.basic_info.globalParameter && response.basic_info.globalParameter.crm_account_bind == -1) {
                // 益生crm会员绑定
                store.commit("setCrmBind", true);
              }

              tempInfo(response.basic_info.home);
              if (response.basic_info.lang) {
                localStorage.setItem("mailLanguage", JSON.stringify(response.basic_info.lang));
                localStorage.setItem("balanceLang", Fun.getCustomTextLang('member_center.credit','余额'));
                localStorage.setItem("integralLang", Fun.getCustomTextLang('member_center.credit1','积分'));
                store.commit("setShopLanguage", response.basic_info.lang);
                getLanguage(response.basic_info.lang.plugin_language);
              }

              if(response.basic_info.plugin_setting && response.basic_info.plugin_setting.translation_component && response.basic_info.plugin_setting.translation_component.is_open){
                translateJsInit();//使用translate.js快速实现当前页面语种切换的能力，https://translate.zvo.cn/index.html
              }
              if (response.basic_info.home && response.basic_info.home != null && response.basic_info.home.memberinfo && response.basic_info.home.memberinfo != null) {
                window.localStorage.uid = response.basic_info.home.memberinfo.uid;
              }
              localStorage.setItem("globalParameter", JSON.stringify(response.basic_info.globalParameter));
              store.commit("setImagePrefix", response.basic_info.host);
              store.commit("setCartNum", response.basic_info.globalParameter.cart_num);

              window.popularizeYZ = response.basic_info.popularize_page;
              window.yz_bd = window.popularizeYZ.baidu;

              // 设置 CSS 变量，全局主题色
              let root = document.querySelector(":root");
              root.style.setProperty("--themeBaseColor", response.basic_info.theme_color);

              //加载图标主题色
              root.style.setProperty("--themeLoadingColor", response.basic_info.theme_color);
              // 设置 CSS 变量，全局主题色   end

              popularize_page_permission();
            }
            if (response.validate_page) {
              getInvite(response.validate_page);
            }
            return JSON.parse(JSON.stringify(response));
          }
        })
        .then(response => {
          resolve(response);
        })
        .catch(err => {
          storeOption.state.isloadding = false;
          console.log(err, "网络请求，无响应！");
          //   reject({ status: "网络请求，无响应" });
        });
    });
  },
  // POST请求  FormData 表单数据

  post(url, formData, message, flag, pc_type) {
    if (!url) {
      console.log("输入url为空");
      return;
    }
    try {
      const controller = new AbortController();
      var { signal } = controller;
      if (abortSignalControllers.length > 0 && flag) {
        const oldcontroller = abortSignalControllers[abortSignalControllers.length - 1];
        oldcontroller.abort();
      }
      abortSignalControllers.push(controller);
    } catch (error) {
      console.log("该浏览器暂不支持 AbortController ！");
    }

    let level = window.localStorage.getItem("level");
    let i = Fun.getKeyByI();
    let mid = Fun.getKeyByMid();
    let type = pc_type || Fun.getTyep();
    let shop_id = Fun.getKeyByMicroShopId();
    let v_id = window.localStorage.getItem("vid");
    let cicleInvitationId = window.localStorage.getItem("circle_invitation_id");
    let sessionid = Fun.getSession();
    let token = Fun.getToken();
    let webToken = localStorage.getItem("token");
    let uid = localStorage.getItem("loginUid");
    let uuid = window.localStorage.uuid;
    // let _thirdpartySSH = Fun.getKey("scope") != 'yearendbox' && Fun.getKey("scope") != 'jinepay' && Fun.getKey("scope") != 'yzx_pay';//第三方免登录  临时更改年末礼盒
    let _thirdpartySSH = Fun.getKey("scope") != 'jinepay' && Fun.getKey("scope") != 'yzx_pay';//第三方免登录
    if (!uuid) {
      uuid = 0;
    }

    let baseUrl = "/addons/yun_shop/api.php?i=" + i + "&uuid=" + uuid + "&type=" + type;
    if (mid) {
      baseUrl += "&mid=" + mid;
    }
    if (Fun.getKey("alipay_token")){
      baseUrl += `&min_token=${Fun.getKey("alipay_token")}`;
      try {
        my.getEnv(function (res) {
          console.log(res.miniprogram,'+++my.getEnv'); //true
          window.alipaymini = res.miniprogram;
        });
      } catch (error) {
        console.log(error,'+++my.getEnv')
      }
    }
    if (shop_id) {
      baseUrl += "&shop_id=" + shop_id;
    }
    if (window.localStorage.getItem('app_id')){
      baseUrl += `&app_id=${window.localStorage.getItem('app_id')}`
    }
    // let ua = window.navigator.userAgent.toLowerCase();
    if (isInWechatMp()) {
      baseUrl += "&miniProgram=1";
      let min_token = sessionStorage.getItem("min_token") || null; //小程序web-view免登录
      if(min_token) baseUrl = `${baseUrl}&min_token=${min_token}`;
    }

    let supplier_alone_id = Fun.getKey('supplier_alone_id') || sessionStorage.getItem("supplier_alone_id") || null; //供应商独立模板，获取供应商id
    if(supplier_alone_id){
      baseUrl += "&supplier_alone_id=" + supplier_alone_id + "&locale_code=" + $i18n.locale;
    }

    if (Fun.getKey("client") === "work" || window.localStorage.getItem("client")) {
      // 判断是否从企业微信侧边栏进入
      window.localStorage.setItem("client", "work");
      baseUrl += "&client=work";
      // baseUrl += "&crop_id="+ Fun.getKey("crop_id");
    }

    baseUrl += "&version=v1.1.149";

    if (Fun.isCPS() && Fun.isCPSAPPI()) {
      baseUrl += "&cps_h5=1";
    }

    //specialFilterApi 一些需要特殊过滤的接口,这些不需要validate_page
    let specialFilterApi = [
      'shop.FrontendError.do-log','member.login.index','member.member.wxJsSdkConfig','member.login.login-mode','home-page.getCaptcha',
      'member.register.sendCodeV2','member.member.prepBind','member.member.bindMobile','plugin.car-manage.frontend.controllers.car.bind-car'
    ]
    let _isSpecialFilterApi = true;
    for (let i = 0; i < specialFilterApi.length; i++) {
      if (url.indexOf(specialFilterApi[i]) > -1 ) {
        _isSpecialFilterApi = false;//拦截，该接口不需要传validate_page
      }
    }

    if (
      window.yzFirstlogin === 0 &&
      window.yzValidate_page === 0 &&
      _isSpecialFilterApi &&
      url.indexOf("plugin.diyform.api.diy-form.save-diy-form-data") < 0
    ) {
      baseUrl = baseUrl + "&validate_page=1";
    }
    if ((window.yzFirstlogin === 1 && _isSpecialFilterApi) || url.indexOf("finance.income-page.index") >= 0) {
      window.yzFirstlogin = 0;
      baseUrl = baseUrl + "&basic_info=1&validate_page=1";
      // if(Fun.getKey("scope") == 'yearendbox'){
      //   baseUrl += `&scope=yearendbox&accessCode=${Fun.getKey("accessCode")}`;
      // }
      if(Fun.getKey("scope") == 'jinepay'){
        baseUrl += `&scope=jinepay&data=${Fun.getKey("data")}`;
      }
      if(Fun.getKey("scope") == 'yzx_pay'){
        baseUrl += `&scope=yzx_pay&yzx_token=${Fun.getKey("yzx_token")}`;
      }
    } else if (!store.state.temp.mailInfo) {
      baseUrl = baseUrl + "&basic_info=1";
      // if(Fun.getKey("scope") == 'yearendbox'){
      //   baseUrl += `&scope=yearendbox&accessCode=${Fun.getKey("accessCode")}`;
      // }
      if(Fun.getKey("scope") == 'jinepay'){
        baseUrl += `&scope=jinepay&data=${Fun.getKey("data")}`;
      }
      if(Fun.getKey("scope") == 'yzx_pay'){
        baseUrl += `&scope=yzx_pay&yzx_token=${Fun.getKey("yzx_token")}`;
      }
    }

    if (v_id) {
      baseUrl = baseUrl + "&vid=" + v_id;
    }
    if (cicleInvitationId) {
      baseUrl += "&circle_invitation_id=" + cicleInvitationId;
    }

    if (level) {
      baseUrl += "&level=" + level;
      let province_id = window.localStorage.getItem("province_id");
      let city_id = window.localStorage.getItem("city_id");
      let district_id = window.localStorage.getItem("district_id");
      let street_id = window.localStorage.getItem("street_id");
      if (province_id) {
        baseUrl += "&province_id=" + province_id;
      }
      if (city_id) {
        baseUrl += "&city_id=" + city_id;
      }
      if (district_id) {
        baseUrl += "&district_id=" + district_id;
      }
      if (street_id) {
        baseUrl += "&street_id=" + street_id;
      }
    }

    let app_token = "";
    if (Fun.isCPS()) {
      let ua = window.navigator.userAgent.toLowerCase();
      if (ua.indexOf("yz_cps02") > -1) {
        if (Fun.isIosOrAndroid() === "ios") {
          app_token = getKeyIIOS().token;
        } else {
          if (getKeyIAndroid()) {
            app_token = getKeyIAndroid().token;
          }
        }
      }
    }

    if (message == null || message == undefined) {
      store.state.isloadding = false;
    } else {
      storeOption.state.isloadding = true;
    }

    if (
      window.location.href.indexOf("scope") > -1 &&
      window.location.href.indexOf("appid") > -1 &&
      window.location.href.indexOf("mob_user") > -1 &&
      window.location.href.indexOf("timestamp") > -1 &&
      window.location.href.indexOf("sign") > -1
    ) {
      console.log("dwwwwwwwwwwwwwwwwwwwwwwwwwwww12")
      if (Fun.isCPS() && !Fun.isCPSAPPI()) {
        baseUrl += "&route=";
        console.log("cps 不同域名或i");
      } else {
        if (app_token) {
          baseUrl += "&app_token=" + app_token;
        }
        if (window.location.href.indexOf("open_id") > -1) {
          console.log("dwwwwwwwwwwwwwwwwwwwwwwwwwwww")
          baseUrl += `&open_id=${Fun.getKey("open_id")}`;
        }
        baseUrl +=
          "&scope=" +
          Fun.getKey("scope") +
          "&appid=" +
          Fun.getKey("appid") +
          "&mob_user=" +
          Fun.getKey("mob_user") +
          "&timestamp=" +
          Fun.getKey("timestamp") +
          "&sign=" +
          Fun.getKey("sign") +
          "&route=";
        if (!window.localStorage.getItem("mob_user") && Fun.getKey("mob_user") != 0) {
          setTimeout(() => {
            window.localStorage.setItem("scope", Fun.getKey("scope"));
            window.localStorage.setItem("appid", Fun.getKey("appid"));
            window.localStorage.setItem("mob_user", Fun.getKey("mob_user"));
            window.localStorage.setItem("timestamp", Fun.getKey("timestamp"));
            window.localStorage.setItem("sign", Fun.getKey("sign"));
          }, 200);
        }
        console.log("freeLogin cps");
      }
    } else if (
      window.localStorage.getItem("scope") &&
      window.localStorage.getItem("appid") &&
      window.localStorage.getItem("mob_user") &&
      window.localStorage.getItem("timestamp") &&
      window.localStorage.getItem("sign")
    ) {
      if (app_token) {
        baseUrl += "&app_token=" + app_token;
      }
      baseUrl +=
        "&scope=" +
        window.localStorage.getItem("scope") +
        "&appid=" +
        window.localStorage.getItem("appid") +
        "&mob_user=" +
        window.localStorage.getItem("mob_user") +
        "&timestamp=" +
        window.localStorage.getItem("timestamp") +
        "&sign=" +
        window.localStorage.getItem("sign") +
        "&route=";
      console.log("freeLogin2");
    } else if (
      window.location.href.indexOf("scope") > -1 &&
      window.location.href.indexOf("appid") > -1 &&
      window.location.href.indexOf("mob_parent") > -1 &&
      window.location.href.indexOf("mob_user") > -1 &&
      window.location.href.indexOf("timetamp") > -1 &&
      window.location.href.indexOf("sign") > -1
    ) {
      baseUrl +=
        "&scope=" +
        Fun.getKey("scope") +
        "&appid=" +
        Fun.getKey("appid") +
        "&mob_parent=" +
        Fun.getKey("mob_parent") +
        "&mob_user=" +
        Fun.getKey("mob_user") +
        "&timetamp=" +
        Fun.getKey("timetamp") +
        "&sign=" +
        Fun.getKey("sign") +
        "&route=";
      if (!window.localStorage.getItem("mob_user") && Fun.getKey("mob_user") != 0) {
        window.localStorage.setItem("scope", Fun.getKey("scope"));
        window.localStorage.setItem("appid", Fun.getKey("appid"));
        window.localStorage.setItem("mob_parent", Fun.getKey("mob_parent"));
        window.localStorage.setItem("mob_user", Fun.getKey("mob_user"));
        window.localStorage.setItem("timetamp", Fun.getKey("timetamp"));
        window.localStorage.setItem("sign", Fun.getKey("sign"));
      }
      console.log("haifen");
    } else if (
      window.localStorage.getItem("scope") &&
      window.localStorage.getItem("appid") &&
      window.localStorage.getItem("mob_parent") &&
      window.localStorage.getItem("mob_user") &&
      window.localStorage.getItem("timetamp") &&
      window.localStorage.getItem("sign")
    ) {
      baseUrl +=
        "&scope=" +
        window.localStorage.getItem("scope") +
        "&appid=" +
        window.localStorage.getItem("appid") +
        "&mob_parent=" +
        window.localStorage.getItem("mob_parent") +
        "&mob_user=" +
        window.localStorage.getItem("mob_user") +
        "&timetamp=" +
        window.localStorage.getItem("timetamp") +
        "&sign=" +
        window.localStorage.getItem("sign") +
        "&route=";
      console.log("haifen2");
    } else if (window.location.href.indexOf("#/cashier_pay/") > -1 && url.indexOf("member.login.check-login") < 0) {
      baseUrl += "&scope=base&route=";
    } else if (_thirdpartySSH && window.location.href.indexOf("#/home?") > 0 && url.indexOf("member.login.check-login") < 0) {
      baseUrl += "&scope=home&route=";
    } else if (_thirdpartySSH && window.location.href.indexOf("#/newDiy?") > 0 && url.indexOf("member.login.check-login") < 0) {
      baseUrl += "&scope=home&route=";
    } else if (_thirdpartySSH && (isPassUrl() == true && url.indexOf("member.login.check-login") < 0 && url.indexOf("member.member-cart.store") < 0) || url.indexOf("shop.FrontendError.do-log") > 0) {
      baseUrl += "&scope=pass&route=";
    } else {
      baseUrl += "&route=";
    }
    return new Promise(function(resolve, reject) {
      url = baseUrl + url;

      if (token) {
        url = url + "&app_type=wechat" + "&3rd_session=" + sessionid + "&session_id=" + token;
      }

      // Authorization要删
      let headers = {
        "Content-Type": "application/json",
        Authorization: "Basic " + base64_encode(uid + ":" + webToken)
      };

      if (window.new_page_comeIn != 2) {
        // 浏览足迹  new_page_comeIn == 2为页面第一个请求接口
        headers["local-url"] = `/${window.location.href.match(/\#\/(\S*)\?/)[1]}`;
        headers["full-url"] = `${window.location.href}`;
        window.new_page_comeIn = 2;
      }

      fetch(url, {
        method: "POST",
        headers: headers,
        body: JSON.stringify(formData),
        credentials: "include",
        signal: signal && !signal.aborted ? signal : null
      })
        .then(response => {
          if (response.ok) {
            return response.json();
          } else {
            reject({ status: response.status });
          }

          storeOption.state.isloadding = false;
        })
        .then(response => {
          storeOption.state.isloadding = false;
          if (response.result == 0 && !Fun.isTextEmpty(response.data) && response.data.status == "number") {
            window.location.href = Fun.getSiteRoot() + "/addons/yun_shop/" + "?menu#" + "/member?i=" + Fun.getKeyByI() + "&type=" + Fun.getTyep() + "&mid=" + Fun.getKeyByMid();
            Toast(response.msg);
            return;
          }
          if (response.result == 0 && !Fun.isTextEmpty(response.data) && response.data.login_status == -1) {
            window.location.href = Fun.getSiteRoot() + "/addons/yun_shop/" + "?menu#" + "/member/blacklist?i=" + Fun.getKeyByI();
            return;
          }
          if (response.result == 0 && !Fun.isTextEmpty(response.data) && response.data.status == -3) {
            window.location.href = Fun.getSiteRoot() + "/addons/yun_shop/" + "?menu#" + "/member/mandate?i=" + Fun.getKeyByI();
            return;
          }

          if (response.result == 0 && response.data == -1) {
            window.location.href = Fun.getSiteRoot() + "/addons/yun_shop/" + "?menu#" + "/CloseSite?i=" + Fun.getKeyByI();
            return;
          }
          if (response.result == 0 && !Fun.isTextEmpty(response.data) && response.data.status == -2) {
            window.location.href = Fun.getSiteRoot() + "/addons/yun_shop/" + "?menu#" + "/404?i=" + Fun.getKeyByI();
            return;
          }
          if (response.result == 0 && !Fun.isTextEmpty(response.data) && (response.data.task_package_invite_code == -1 || response.data.task_package_real_name_auth == -1)){
            if(response.data.task_package_invite_code == -1) {
              let MinUrl = Fun.getSiteRoot() + "/addons/yun_shop/?menu#/taskPackage/middle?i=" + Fun.getKeyByI() + "&type=" + Fun.getTyep() + "&mid=" + Fun.getKeyByMid();
              window.location.href = MinUrl;
              return
            };
            if(response.data.task_package_real_name_auth == -1) {
              store.commit("setCallback", window.location.href);
              let MinUrl = Fun.getSiteRoot() + "/addons/yun_shop/?menu#/personBank?from=bindRealName&i=" + Fun.getKeyByI() + "&type=" + Fun.getTyep() + "&mid=" + Fun.getKeyByMid();
              window.location.href = MinUrl;
              return
            }
          }
          if (response.result == 0 && !Fun.isTextEmpty(response.data) && response.data.login_status != undefined && response.data.login_status == 0) {
            window.yzFirstlogin = 1;
            window.localStorage.setItem("isWxLogin", 1);
            if (!window.firstLogin) {
              window.firstLogin = 1;
              console.log("微信登录");
              let login_jump_url = response.data.login_url + "&yz_redirect=" + base64_encode(document.location.href);
              if (Fun.getKey("client") === "work" || window.localStorage.getItem("client")) {
                // 是否从企业微信侧边栏进入
                login_jump_url = response.data.login_url + "&crop_id="+ Fun.getKey("crop_id") + "&client=work&yz_redirect=" + base64_encode(document.location.href);
                window.location.href = login_jump_url;//企业微信不统一wxRedirectLogin跳转的原因：苹果电脑出现闪退，原因不详
                return;
              } else if(response.data.scope && response.data.scope == 'snsapi_base'){
                window.location.href = login_jump_url;//静默登录
                return;
              }
              wxRedirectLogin(document.location.href);
            }
            reject({ msg: "请登录" }); //直接报错
            return response;
          } else if (response.result == 0 && !Fun.isTextEmpty(response.data) && response.data.login_status != undefined && response.data.login_status == 1) {
            window.yzFirstlogin = 1;
            window.localStorage.setItem("isWxLogin", -1);
            if (document.location.href.indexOf("/login?") == -1) {
              let _locationHref = document.location.href;
              if (window.self !== window.top) {
                _locationHref = window.parent.location.href;//在iframe环境打开
              }
              sessionStorage.setItem("yz_redirect", base64_encode(_locationHref));
            }

            // try {
            //   let basic_info = JSON.parse(localStorage.getItem("yz_basic_info"))||{};
            //   let is_year_end_box_login = basic_info.plugin_setting&&basic_info.plugin_setting.is_year_end_box_login?basic_info.plugin_setting.is_year_end_box_login:false;
            //   if(is_year_end_box_login){
            //     authYear();
            //     return;
            //   }
            // } catch (error) {
            //   console.log("年末礼盒=====",error);
            // }

            if (!window.firstLogin) {
              console.log("登录");
              if (Fun.isCPS() && Fun.isCPSAPPI()) {
                window.firstLogin = 1;
                if (Fun.isIosOrAndroid() === "ios") {
                  callIOS({ body: "callIOS" });
                } else {
                  callAndroid();
                }

                setTimeout(() => {
                  // 防止聚合APP切换不同公众号没有再次登录
                  window.firstLogin = 0;
                }, 3000);
              } else {
                console.log(Fun.getKey("scope"),'ddddddddddddddd')
                window.location.href = Fun.getSiteRoot() + "/addons/yun_shop/" + "?menu#" + "/login?i=" + response.data.i + "&type=" + Fun.getTyep() + "&mid=" + response.data.mid;
              }
            }

            reject({ msg: "请登录" }); //直接报错
            return response;
          } else {
            if (response.basic_info) {
              localStorage.setItem("yz_basic_info", JSON.stringify(response.basic_info));
              if (response.basic_info.consolidated_payment) {
                localStorage.setItem("consolidated_payment", response.basic_info.consolidated_payment == "1" ? true : false);
              }
              if (response.basic_info.plugin_setting) {
                localStorage.setItem("plugin_setting", JSON.stringify(response.basic_info.plugin_setting));
              }
              // 跳转PC端代码
              if (!Fun.isWXWork() && response.basic_info.plugin_setting && response.basic_info.plugin_setting.pc_terminal && response.basic_info.plugin_setting.pc_terminal.enable == 1) {
                jumpH5(response.data);
              }
              // 跳转PC端代码end

              if (response.basic_info.globalParameter && response.basic_info.globalParameter.crm_account_bind == -1) {
                // 益生crm会员绑定
                store.commit("setCrmBind", true);
              }

              tempInfo(response.basic_info.home);
              if (response.basic_info.lang) {
                localStorage.setItem("mailLanguage", JSON.stringify(response.basic_info.lang));
                localStorage.setItem("balanceLang", Fun.getCustomTextLang('member_center.credit','余额'));
                localStorage.setItem("integralLang", Fun.getCustomTextLang('member_center.credit1','积分'));
                store.commit("setShopLanguage", response.basic_info.lang);
                getLanguage(response.basic_info.lang.plugin_language);
              }
              if(response.basic_info.plugin_setting && response.basic_info.plugin_setting.translation_component && response.basic_info.plugin_setting.translation_component.is_open){
                translateJsInit();//使用translate.js实现当前页面语种切换的能力，https://translate.zvo.cn/index.html
              }
              if (response.basic_info.home && response.basic_info.home != null && response.basic_info.home.memberinfo && response.basic_info.home.memberinfo != null) {
                window.localStorage.uid = response.basic_info.home.memberinfo.uid;
              }
              localStorage.setItem("globalParameter", JSON.stringify(response.basic_info.globalParameter));

              store.commit("setImagePrefix", response.basic_info.host);
              store.commit("setCartNum", response.basic_info.globalParameter ? response.basic_info.globalParameter.cart_num : "");

              window.popularizeYZ = response.basic_info.popularize_page;
              window.yz_bd = window.popularizeYZ.baidu;

              // 设置 CSS 变量，全局主题色
              let root = document.querySelector(":root");
              root.style.setProperty("--themeBaseColor", response.basic_info.theme_color);

              //加载图标主题色
              root.style.setProperty("--themeLoadingColor", response.basic_info.theme_color);
              // 设置 CSS 变量，全局主题色   end

              popularize_page_permission();
            }
            if (response.validate_page) {
              getInvite(response.validate_page);
            }

            return response;
          }
        })
        .then(response => {
          resolve(response);
        })
        .catch(err => {
          storeOption.state.isloadding = false;
          if (err.name === "AbortError") {
            console.log("手动中止请求接口");
          } else {
            console.log("网络请求，无响应！", err);
            reject({ status: "网络请求，无响应！" });
          }
        });
    });
  }
};
